import axios, { type AxiosRequestHeaders } from "axios";
import storage from "./storage";
import { ElMessage, ElLoading } from "element-plus";
import router from "../router";
import dayjs from "dayjs";
let loadingInstance: any;
let requestCount = 0;

const instance = axios.create({
  baseURL: import.meta.env.VITE_URL,
  timeout: 60000,
});

const showLoading = () => {
  if (requestCount === 0) {
    loadingInstance = ElLoading.service({
      fullscreen: true,
      text: "数据加载中",
      background: "rgba(0, 0, 0, 0)",
    });
  }
  requestCount++;
};

const hideLoading = () => {
  requestCount--;
  if (requestCount === 0) {
    if (loadingInstance) {
      loadingInstance.close();
    }
  }
};
var globConfig = {} as any;
instance.interceptors.request.use(
  (config: any) => {
    if (!config.headers) {
      config.headers = {} as AxiosRequestHeaders;
    }
    if (storage.get("token")) {
      config.headers.authorization = `Bearer ${storage.get("token")}`;
    }
    showLoading();
    globConfig = config;
    return config;
  },
  (error: any) => {
    hideLoading();
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  (response: any) => {
    hideLoading();
    if (globConfig.responseType == "blob") {
      const { data, status } = response;
      if (status != 200) {
        return Promise.reject(response);
      }
      // || response.headers["content-disposition"]
      let fileName = `账单数据表${dayjs().format("YYYYMMDDHHmmss")}`;
      let contentType = response.headers["content-type"];
      let blob = new Blob([data], { type: contentType });
      // 下载文件
      if ("download" in document.createElement("a")) {
        // 非IE下载
        const a = document.createElement("a");
        const downloadUrl = window.URL.createObjectURL(blob);
        a.href = downloadUrl;
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(downloadUrl);
      } else {
        // IE下载
        (navigator as any).msSaveBlob(blob, fileName);
      }
      return Promise.resolve("下载文件成功");
    }

    let code = response.data.code;
    if ([200].includes(code)) {
      return Promise.resolve(response.data);
    } else {
      if ([401, 403].includes(code)) {
        storage.clear();
        router.replace("/login");
      }
      if ([201].includes(code)) {
        ElMessage.error(response.data.message);
        return Promise.resolve();
      }

      ElMessage.error(response.data.message);
      return Promise.resolve();
    }
  },
  (error: any) => {
    hideLoading();
    if (error.code == "ERR_NETWORK" || error.code == "ECONNABORTED") {
      return console.log("服务器网络异常,请连接网络刷新后重试");
    }
    return Promise.reject(error.response && error.response.data);
  }
);

export { instance };
